<script lang="ts" setup>
import type {
  ApiResponseVoid,
  ChangePasswordRequest,
  UserResponse,
  UserUpdateRequest,
} from '#/api/openapi';

import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { usePreferences } from '@vben/preferences';

import {
  EyeInvisibleOutlined as EyeInvisible,
  EyeOutlined as EyeVisible,
} from '@ant-design/icons-vue';
import {
  CheckOne,
  CloseOne,
  Edit,
  Key,
  Logout,
  Save,
  User,
} from '@icon-park/vue-next';
import { message } from 'ant-design-vue';

import { client } from '#/api';
import Button from '#/components/fluentui/Button.vue';
import Input from '#/components/fluentui/TextInput.vue';
import { useAuthStore } from '#/store';

const { isDark } = usePreferences();
const router = useRouter();
const authStore = useAuthStore();

// 用户信息状态
const userInfo = ref<null | UserResponse>(null);
const loading = ref(false);
const isEditing = ref(false);

// 编辑表单数据
const editForm = reactive({
  displayName: '',
  email: '',
  avatarUrl: '',
});

// 表单验证错误
const editErrors = reactive({
  displayName: '',
  email: '',
});

// 密码修改相关状态
const showPasswordDialog = ref(false);
const passwordLoading = ref(false);
const showCurrentPassword = ref(false);
const showNewPassword = ref(false);
const showConfirmPassword = ref(false);

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 密码表单验证错误
const passwordErrors = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 头像上传相关状态
const showAvatarUpload = ref(false);
const avatarUploadLoading = ref(false);
const avatarPreview = ref<string>('');

// 退出登录确认对话框
const showLogoutDialog = ref(false);

// 邮箱正则验证
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-z]{2,}$/i;

// 计算属性：用户角色显示
const roleDisplay = computed(() => {
  switch (userInfo.value?.role) {
    case 'ADMIN': {
      return '管理员';
    }
    case 'USER': {
      return '普通用户';
    }
    default: {
      return '未知';
    }
  }
});
const fmtCreatedAt = computed(() => formatDate(userInfo.value?.createdAt));
const fmtLastLogin = computed(() => formatDate(userInfo.value?.lastLogin));
// 计算属性：账户状态显示
const statusDisplay = computed(() => {
  return userInfo.value?.enabled ? '正常' : '已禁用';
});

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;
    const { data } = await client.user.getCurrentUser();

    if (data.success && data.data) {
      userInfo.value = data.data;
      // 初始化编辑表单数据
      editForm.displayName = data.data.displayName || '';
      editForm.email = data.data.email || '';
      editForm.avatarUrl = data.data.avatarUrl || '';
    } else {
      message.error(data.message || '获取用户信息失败');
    }
  } catch (error: any) {
    console.error('获取用户信息失败:', error);
    message.error(error.message || '获取用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 开始编辑
const startEdit = () => {
  isEditing.value = true;
  // 重新设置表单数据，防止之前的修改影响
  editForm.displayName = userInfo.value?.displayName || '';
  editForm.email = userInfo.value?.email || '';
  editForm.avatarUrl = userInfo.value?.avatarUrl || '';
  // 清除错误信息
  editErrors.displayName = '';
  editErrors.email = '';
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  // 重置表单数据
  editForm.displayName = userInfo.value?.displayName || '';
  editForm.email = userInfo.value?.email || '';
  editForm.avatarUrl = userInfo.value?.avatarUrl || '';
  // 清除错误信息
  editErrors.displayName = '';
  editErrors.email = '';
};

// 验证编辑表单
const validateEditForm = (): boolean => {
  editErrors.displayName = '';
  editErrors.email = '';

  let isValid = true;

  if (!editForm.displayName.trim()) {
    editErrors.displayName = '请输入显示名称';
    isValid = false;
  } else if (editForm.displayName.length > 50) {
    editErrors.displayName = '显示名称不能超过50个字符';
    isValid = false;
  }

  if (!editForm.email.trim()) {
    editErrors.email = '请输入邮箱地址';
    isValid = false;
  } else if (!emailRegex.test(editForm.email)) {
    editErrors.email = '请输入有效的邮箱地址';
    isValid = false;
  }

  return isValid;
};

// 保存用户信息
const saveUserInfo = async () => {
  if (!validateEditForm()) {
    return;
  }

  if (!userInfo.value?.id) {
    message.error('用户信息异常，请刷新页面重试');
    return;
  }

  try {
    loading.value = true;

    const updateRequest: UserUpdateRequest = {
      displayName: editForm.displayName,
      email: editForm.email,
      avatarUrl: editForm.avatarUrl || undefined,
    };

    const { data } = await client.user.updateUser(
      userInfo.value.id,
      updateRequest,
    );
    if (data.success && data.data) {
      userInfo.value = data.data;
      isEditing.value = false;
      message.success('用户信息更新成功');
    } else {
      message.error(data.message || '更新用户信息失败');
    }
  } catch (error: any) {
    console.error('更新用户信息失败:', error);
    message.error(error.message || '更新用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 验证密码表单
const validatePasswordForm = (): boolean => {
  passwordErrors.currentPassword = '';
  passwordErrors.newPassword = '';
  passwordErrors.confirmPassword = '';

  let isValid = true;

  if (!passwordForm.currentPassword.trim()) {
    passwordErrors.currentPassword = '请输入当前密码';
    isValid = false;
  }

  if (!passwordForm.newPassword.trim()) {
    passwordErrors.newPassword = '请输入新密码';
    isValid = false;
  } else if (passwordForm.newPassword.length < 6) {
    passwordErrors.newPassword = '新密码长度不能少于6位';
    isValid = false;
  }

  if (!passwordForm.confirmPassword.trim()) {
    passwordErrors.confirmPassword = '请确认新密码';
    isValid = false;
  } else if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    passwordErrors.confirmPassword = '两次输入的密码不一致';
    isValid = false;
  }

  return isValid;
};

// 修改密码
const changePassword = async () => {
  if (!validatePasswordForm()) {
    return;
  }

  try {
    passwordLoading.value = true;

    const changePasswordRequest: ChangePasswordRequest = {
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword,
    };

    const response: ApiResponseVoid = await client.user.changePassword(
      changePasswordRequest,
    );

    if (response.success) {
      message.success('密码修改成功，请重新登录');
      // 清空表单
      passwordForm.currentPassword = '';
      passwordForm.newPassword = '';
      passwordForm.confirmPassword = '';
      showPasswordDialog.value = false;

      // 延迟跳转到登录页面
      setTimeout(() => {
        authStore.logout();
        router.push('/login');
      }, 1500);
    } else {
      message.error(response.message || '密码修改失败');
    }
  } catch (error: any) {
    console.error('密码修改失败:', error);
    message.error(error.message || '密码修改失败');
  } finally {
    passwordLoading.value = false;
  }
};

// 打开密码修改对话框
const openPasswordDialog = () => {
  showPasswordDialog.value = true;
  // 清空表单
  passwordForm.currentPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  // 清除错误信息
  passwordErrors.currentPassword = '';
  passwordErrors.newPassword = '';
  passwordErrors.confirmPassword = '';
  // 重置密码显示状态
  showCurrentPassword.value = false;
  showNewPassword.value = false;
  showConfirmPassword.value = false;
};

// 关闭密码修改对话框
const closePasswordDialog = () => {
  showPasswordDialog.value = false;
  // 清空表单
  passwordForm.currentPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  // 清除错误信息
  passwordErrors.currentPassword = '';
  passwordErrors.newPassword = '';
  passwordErrors.confirmPassword = '';
};

// 处理头像文件选择
const handleAvatarFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件');
    return;
  }

  // 验证文件大小（限制5MB）
  if (file.size > 5 * 1024 * 1024) {
    message.error('图片大小不能超过5MB');
    return;
  }

  // 创建预览
  const reader = new FileReader();
  reader.addEventListener('load', (e) => {
    avatarPreview.value = e.target?.result as string;
  });
  reader.readAsDataURL(file);

  // 上传头像
  uploadAvatar(file);
};

// 上传头像
const uploadAvatar = async (file: File) => {
  try {
    avatarUploadLoading.value = true;

    // 创建FormData
    const formData = new FormData();
    formData.append('file', file);

    // 使用头像上传API
    const response = await client.avatar.uploadAvatarFile();

    if (response.data) {
      message.success('头像上传成功');
      // 重新获取用户信息以更新头像
      await fetchUserInfo();
      showAvatarUpload.value = false;
      avatarPreview.value = '';
    } else {
      message.error('头像上传失败');
    }
  } catch (error: any) {
    console.error('头像上传失败:', error);
    message.error(error.message || '头像上传失败');
  } finally {
    avatarUploadLoading.value = false;
  }
};

// 删除头像
const deleteAvatar = async () => {
  try {
    loading.value = true;

    const response = await client.avatar.deleteAvatar();

    if (response.data) {
      message.success('头像删除成功');
      // 重新获取用户信息以更新头像
      await fetchUserInfo();
    } else {
      message.error('头像删除失败');
    }
  } catch (error: any) {
    console.error('头像删除失败:', error);
    message.error(error.message || '头像删除失败');
  } finally {
    loading.value = false;
  }
};

// 打开头像上传对话框
const openAvatarUpload = () => {
  showAvatarUpload.value = true;
  avatarPreview.value = '';
};

// 关闭头像上传对话框
const closeAvatarUpload = () => {
  showAvatarUpload.value = false;
  avatarPreview.value = '';
};

// 格式化日期
const formatDate = (dateString?: string): string => {
  if (!dateString) return '未知';
  try {
    return new Date(dateString).toLocaleString('zh-CN');
  } catch {
    return '未知';
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 退出登录
const handleLogout = async () => {
  try {
    await authStore.logout();
  } catch (error: any) {
    console.error('退出登录失败:', error);
    message.error(error.message || '退出登录失败');
  }
};

// 显示退出登录确认对话框
const showLogoutConfirm = () => {
  showLogoutDialog.value = true;
};

// 关闭退出登录确认对话框
const closeLogoutDialog = () => {
  showLogoutDialog.value = false;
};

// 确认退出登录
const confirmLogout = async () => {
  showLogoutDialog.value = false;
  await handleLogout();
};

// 页面挂载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<template>
  <div
    class="bg-background text-foreground mx-auto min-h-screen max-w-4xl px-6 py-8"
    :data-theme="isDark ? 'dark' : 'light'"
  >
    <!-- 页面标题 -->
    <div class="mb-8 flex items-center justify-between">
      <div>
        <h1 class="mb-2 text-3xl font-bold">用户信息</h1>
        <p class="text-gray-600 dark:text-gray-300">查看和管理您的账户信息</p>
      </div>
      <Button @click="goBack" appearance="subtle" size="medium"> 返回 </Button>
    </div>

    <!-- 加载状态 -->
    <div
      v-if="loading && !userInfo"
      class="flex items-center justify-center py-12"
    >
      <div class="text-center">
        <div
          class="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-2 border-blue-600 border-t-transparent"
        ></div>
        <p class="text-gray-600 dark:text-gray-400">加载中...</p>
      </div>
    </div>

    <!-- 用户信息内容 -->
    <div v-else-if="userInfo" class="space-y-6">
      <!-- 基本信息卡片 -->
      <div
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <div class="mb-4 flex items-center justify-between">
          <h2 class="text-xl font-semibold">基本信息</h2>
          <div class="flex gap-2">
            <Button
              v-if="!isEditing"
              @click="startEdit"
              appearance="primary"
              size="medium"
            >
              <template #start>
                <Edit />
              </template>
              编辑
            </Button>
            <template v-else>
              <Button
                @click="saveUserInfo"
                appearance="primary"
                size="medium"
                :disabled="loading"
              >
                <template #start>
                  <Save />
                </template>
                保存
              </Button>
              <Button
                @click="cancelEdit"
                appearance="subtle"
                size="medium"
                :disabled="loading"
              >
                <template #start>
                  <CloseOne />
                </template>
                取消
              </Button>
            </template>
          </div>
        </div>

        <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
          <!-- 头像 -->
          <div class="col-span-full flex items-center space-x-4">
            <div
              class="relative flex h-16 w-16 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900"
            >
              <img
                v-if="userInfo.avatarUrl"
                :src="userInfo.avatarUrl"
                :alt="userInfo.displayName || userInfo.username"
                class="h-16 w-16 rounded-full object-cover"
              />
              <User v-else class="h-8 w-8 text-blue-600 dark:text-blue-400" />

              <!-- 头像操作按钮 -->
              <div v-if="isEditing" class="absolute -bottom-1 -right-1">
                <Button
                  @click="openAvatarUpload"
                  appearance="primary"
                  size="small"
                  icon-only
                  class="h-6 w-6 rounded-full"
                >
                  <Edit size="12" />
                </Button>
              </div>
            </div>

            <div>
              <div class="flex items-center gap-2">
                <h3 class="font-medium">头像</h3>
                <div v-if="isEditing" class="flex gap-1">
                  <Button
                    @click="openAvatarUpload"
                    appearance="subtle"
                    size="small"
                  >
                    上传
                  </Button>
                  <Button
                    v-if="userInfo.avatarUrl"
                    @click="deleteAvatar"
                    appearance="subtle"
                    size="small"
                    class="text-red-600"
                  >
                    删除
                  </Button>
                </div>
              </div>
              <p class="text-xs text-gray-500 dark:text-gray-400">
                支持 JPG、PNG 格式，大小不超过 5MB
              </p>
            </div>
          </div>

          <!-- 用户名 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              用户名
            </label>
            <Input
              v-model="userInfo.username"
              type="text"
              :disabled="true"
              :class="{ 'border-red-500': editErrors.displayName }"
            />
            <p class="mt-1 text-xs text-gray-500">用户名不可修改</p>
          </div>

          <!-- 显示名称 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              显示名称
            </label>
            <div>
              <Input
                v-model="editForm.displayName"
                type="text"
                :disabled="!isEditing"
                placeholder="请输入显示名称"
                :class="{ 'border-red-500': editErrors.displayName }"
              />
              <p
                v-if="editErrors.displayName"
                class="mt-1 text-xs text-red-600"
              >
                {{ editErrors.displayName }}
              </p>
            </div>
          </div>

          <!-- 邮箱 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              邮箱地址
            </label>

            <div>
              <Input
                v-model="editForm.email"
                type="email"
                :disabled="!isEditing"
                placeholder="请输入邮箱地址"
                :class="{ 'border-red-500': editErrors.email }"
              />
              <p v-if="editErrors.email" class="mt-1 text-xs text-red-600">
                {{ editErrors.email }}
              </p>
            </div>
          </div>

          <!-- 用户角色 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              用户角色
            </label>
            <Input :disabled="true" v-model="roleDisplay" />
          </div>

          <!-- 账户状态 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              账户状态
            </label>
            <div class="mt-1 flex items-center">
              <span
                class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
                :class="
                  userInfo.enabled
                    ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                    : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                "
              >
                {{ statusDisplay }}
              </span>
            </div>
          </div>

          <!-- 创建时间 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              创建时间
            </label>
            <Input :disabled="true" v-model="fmtCreatedAt" />
          </div>

          <!-- 最后登录 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              最后登录
            </label>
            <Input :disabled="true" v-model="fmtLastLogin" />
          </div>
        </div>
      </div>

      <!-- 安全设置卡片 -->
      <div
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <div class="mb-4 flex items-center justify-between">
          <h2 class="text-xl font-semibold">安全设置</h2>
        </div>

        <div class="space-y-4">
          <div
            class="flex items-center justify-between rounded-lg border border-gray-200 p-4 dark:border-gray-600"
          >
            <div>
              <h3 class="font-medium">修改密码</h3>
              <p class="text-sm text-gray-600 dark:text-gray-400">
                定期修改密码以保护账户安全
              </p>
            </div>
            <Button
              @click="openPasswordDialog"
              appearance="primary"
              size="medium"
            >
              <template #start>
                <Key />
              </template>
              修改密码
            </Button>
          </div>

          <!-- 退出登录 -->
          <div
            class="flex items-center justify-between rounded-lg border border-gray-200 p-4 dark:border-gray-600"
          >
            <div>
              <h3 class="font-medium">退出登录</h3>
              <p class="text-sm text-gray-600 dark:text-gray-400">
                结束当前会话，保护账户安全
              </p>
            </div>
            <Button
              @click="showLogoutConfirm"
              appearance="subtle"
              size="medium"
              class="border-red-200 text-red-600 hover:border-red-300 hover:text-red-700"
            >
              <template #start>
                <Logout />
              </template>
              退出登录
            </Button>
          </div>
        </div>
      </div>

      <!-- 头像设置卡片 -->
      <div
        class="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800"
      >
        <div class="mb-4 flex items-center justify-between">
          <h2 class="text-xl font-semibold">头像设置</h2>
          <div class="flex gap-2">
            <Button
              v-if="!showAvatarUpload"
              @click="openAvatarUpload"
              appearance="subtle"
              size="medium"
            >
              <template #start>
                <Edit />
              </template>
              上传头像
            </Button>
            <Button
              v-else
              @click="closeAvatarUpload"
              appearance="subtle"
              size="medium"
            >
              <template #start>
                <CloseOne />
              </template>
              取消上传
            </Button>
          </div>
        </div>

        <div class="flex items-center space-x-4">
          <!-- 头像预览 -->
          <div
            class="flex h-16 w-16 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900"
          >
            <img
              v-if="avatarPreview"
              :src="avatarPreview"
              alt="头像预览"
              class="h-16 w-16 rounded-full object-cover"
            />
            <User
              v-else-if="userInfo.avatarUrl"
              :src="userInfo.avatarUrl"
              :alt="userInfo.displayName || userInfo.username"
              class="h-16 w-16 rounded-full object-cover"
            />
            <User v-else class="h-8 w-8 text-blue-600 dark:text-blue-400" />
          </div>

          <!-- 上传区域 -->
          <div v-if="showAvatarUpload" class="flex-1">
            <input
              type="file"
              accept="image/*"
              @change="handleAvatarFileSelect"
              class="hidden"
              id="avatarFileInput"
            />
            <label
              for="avatarFileInput"
              class="flex cursor-pointer items-center justify-center rounded-md border border-gray-300 bg-gray-50 px-3 py-2 text-sm text-gray-600 transition-all duration-200 hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400"
            >
              <span>选择图片</span>
            </label>
            <p class="mt-2 text-xs text-gray-500">
              支持格式：JPG, PNG, GIF（最大5MB）
            </p>
          </div>
        </div>

        <!-- 删除头像按钮 -->
        <div v-if="userInfo.avatarUrl" class="mt-4">
          <Button
            @click="deleteAvatar"
            size="medium"
            :disabled="loading"
            class="w-full text-red-600"
          >
            <template #start>
              <CloseOne />
            </template>
            删除头像
          </Button>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div
      v-else
      class="rounded-lg border border-gray-200 bg-white p-12 text-center dark:border-gray-700 dark:bg-gray-800"
    >
      <User class="mx-auto h-16 w-16 text-gray-400" />
      <h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">
        无法获取用户信息
      </h3>
      <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
        请刷新页面重试或联系管理员
      </p>
      <Button
        @click="fetchUserInfo"
        appearance="primary"
        size="medium"
        class="mt-4"
      >
        重新加载
      </Button>
    </div>

    <!-- 密码修改对话框 -->
    <div
      v-if="showPasswordDialog"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
    >
      <div
        class="mx-4 w-full max-w-md rounded-lg bg-white p-6 dark:bg-gray-800"
      >
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-semibold">修改密码</h3>
          <button
            @click="closePasswordDialog"
            class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <CloseOne size="20" />
          </button>
        </div>

        <form @submit.prevent="changePassword" class="space-y-4">
          <!-- 当前密码 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              当前密码
            </label>
            <div class="relative mt-1">
              <Input
                v-model="passwordForm.currentPassword"
                :type="showCurrentPassword ? 'text' : 'password'"
                placeholder="请输入当前密码"
                class="block w-full rounded-md border border-gray-300 px-3 py-2 pr-10 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                :class="{ 'border-red-500': passwordErrors.currentPassword }"
              />
              <button
                type="button"
                @click="showCurrentPassword = !showCurrentPassword"
                class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
              >
                <EyeVisible v-if="showCurrentPassword" size="16" />
                <EyeInvisible v-else size="16" />
              </button>
            </div>
            <p
              v-if="passwordErrors.currentPassword"
              class="mt-1 text-xs text-red-600"
            >
              {{ passwordErrors.currentPassword }}
            </p>
          </div>

          <!-- 新密码 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              新密码
            </label>
            <div class="relative mt-1">
              <Input
                v-model="passwordForm.newPassword"
                :type="showNewPassword ? 'text' : 'password'"
                placeholder="请输入新密码"
                class="block w-full rounded-md border border-gray-300 px-3 py-2 pr-10 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                :class="{ 'border-red-500': passwordErrors.newPassword }"
              />
              <button
                type="button"
                @click="showNewPassword = !showNewPassword"
                class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
              >
                <EyeVisible v-if="showNewPassword" size="16" />
                <EyeInvisible v-else size="16" />
              </button>
            </div>
            <p
              v-if="passwordErrors.newPassword"
              class="mt-1 text-xs text-red-600"
            >
              {{ passwordErrors.newPassword }}
            </p>
          </div>

          <!-- 确认新密码 -->
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              确认新密码
            </label>
            <div class="relative mt-1">
              <Input
                v-model="passwordForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入新密码"
                class="block w-full rounded-md border border-gray-300 px-3 py-2 pr-10 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                :class="{ 'border-red-500': passwordErrors.confirmPassword }"
              />
              <button
                type="button"
                @click="showConfirmPassword = !showConfirmPassword"
                class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600"
              >
                <EyeVisible v-if="showConfirmPassword" size="16" />
                <EyeInvisible v-else size="16" />
              </button>
            </div>
            <p
              v-if="passwordErrors.confirmPassword"
              class="mt-1 text-xs text-red-600"
            >
              {{ passwordErrors.confirmPassword }}
            </p>
          </div>

          <!-- 按钮区域 -->
          <div class="flex gap-3 pt-4">
            <Button
              type="submit"
              appearance="primary"
              size="medium"
              :disabled="passwordLoading"
              class="flex-1"
            >
              <template #start>
                <CheckOne v-if="!passwordLoading" />
                <div
                  v-else
                  class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"
                ></div>
              </template>
              {{ passwordLoading ? '修改中...' : '确认修改' }}
            </Button>
            <Button
              @click="closePasswordDialog"
              appearance="subtle"
              size="medium"
              :disabled="passwordLoading"
              class="flex-1"
            >
              取消
            </Button>
          </div>
        </form>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <div
      v-if="showAvatarUpload"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
    >
      <div
        class="mx-4 w-full max-w-md rounded-lg bg-white p-6 dark:bg-gray-800"
      >
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-semibold">更换头像</h3>
          <button
            @click="closeAvatarUpload"
            class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <CloseOne size="20" />
          </button>
        </div>

        <div class="mb-4 flex justify-center">
          <div
            class="flex h-24 w-24 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900"
          >
            <img
              v-if="avatarPreview"
              :src="avatarPreview"
              alt="头像预览"
              class="h-24 w-24 rounded-full object-cover"
            />
            <img
              v-else-if="userInfo?.avatarUrl"
              :src="userInfo.avatarUrl"
              :alt="userInfo.displayName || userInfo.username"
              class="h-24 w-24 rounded-full object-cover"
            />
            <User v-else class="h-12 w-12 text-blue-600 dark:text-blue-400" />
          </div>
        </div>

        <div class="space-y-4">
          <div>
            <input
              type="file"
              accept="image/*"
              @change="handleAvatarFileSelect"
              class="hidden"
              ref="avatarFileInput"
            />
            <Button
              @click="($refs.avatarFileInput as any)?.click()"
              appearance="primary"
              size="large"
              class="w-full"
              :disabled="avatarUploadLoading"
            >
              <template #start>
                <div
                  v-if="avatarUploadLoading"
                  class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"
                ></div>
                <Edit v-else />
              </template>
              {{ avatarUploadLoading ? '上传中...' : '选择图片' }}
            </Button>
          </div>

          <div class="text-center text-xs text-gray-500 dark:text-gray-400">
            支持 JPG、PNG 格式，大小不超过 5MB
          </div>

          <div class="flex gap-3">
            <Button
              @click="closeAvatarUpload"
              appearance="subtle"
              size="medium"
              class="flex-1"
              :disabled="avatarUploadLoading"
            >
              取消
            </Button>
          </div>
        </div>
      </div>
    </div>

    <!-- 退出登录确认对话框 -->
    <div
      v-if="showLogoutDialog"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"
    >
      <div
        class="mx-4 w-full max-w-sm rounded-lg bg-white p-6 dark:bg-gray-800"
      >
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-red-600">确认退出</h3>
          <button
            @click="closeLogoutDialog"
            class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <CloseOne size="20" />
          </button>
        </div>

        <div class="mb-6">
          <p class="text-gray-600 dark:text-gray-400">
            您确定要退出登录吗？退出后需要重新登录才能访问账户。
          </p>
        </div>

        <div class="flex gap-3">
          <Button
            @click="closeLogoutDialog"
            appearance="subtle"
            size="medium"
            class="flex-1"
          >
            取消
          </Button>
          <Button
            @click="confirmLogout"
            appearance="primary"
            size="medium"
            class="flex-1 border-red-600 bg-red-600 hover:border-red-700 hover:bg-red-700"
          >
            <template #start>
              <Logout />
            </template>
            确认退出
          </Button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 确保输入框在深色模式下正常显示 */
input[type='text'],
input[type='email'],
input[type='password'],
input[type='url'] {
  @apply transition-colors duration-200;
}

input[type='text']:focus,
input[type='email']:focus,
input[type='password']:focus,
input[type='url']:focus {
  @apply border-blue-500 ring-1 ring-blue-500;
}

/* 对话框遮罩动画 */
.fixed {
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 对话框内容动画 */
.fixed > div {
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(10px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
